const cp = require('child_process')
const { join } = require('path')

const mongoose = require('mongoose')
const Movie = mongoose.model('Movie')
const Category = mongoose.model('Category')

;(async () => {

  let movies = await Movie.find({
    $or: [
      { video: { $exists: false }},
      { video: null }
    ]
  })


  const script = join(__dirname, '../crawler/video.js')
  const child = cp.fork(script, [])
  let invoked = false

  child.on('error', err => {
    if (invoked) return

    invoked = true
    console.log(err)
  })

  child.on('exit', code => {
    if (invoked) return

    invoked = true
    let err = code === 0 ? null : new Error('exit code' + code)
    if (err) console.log(err)
  })

  child.on('message', async (data) => {
    // 获取 id
    let doubanId = data.doubanId
    // 查找对应电影
    let movie = await Movie.findOne({
      doubanId: doubanId
    })

    // 获取数据 存储
    if (data.video) {
      movie.video = data.video
      movie.cover = data.cover

      await movie.save()
    } else {

      let movieTypes = movie.movieTypes
      // 无数据 删除当前项
      await movie.remove()

      // 遍历 删除分类电影中的 当前电影数据
      for( let i = 0; i < movieTypes.length; i++) {
        let type = movieTypes[i]
        let cat = Category.findOne({
          name: type
        })

        if (cat && cat.movies) { 
          let idx = cat.movies.indexOf(movie._id)

          if (idx > -1) {
            cat.movies = cat.movies.splice(idx, 1)
          }

          await cat.save()
        }
      }
    }
  })
  child.send(movies)
})() 